package com.buaa.divinationmaster;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import android.widget.EditText;
import com.buaa.divinationmaster.algorithm.LenormandInterpreter;
import com.buaa.divinationmaster.utils.ScreenAdaptationUtil;
import com.buaa.divinationmaster.manager.DatabaseManager;
import com.buaa.divinationmaster.manager.LenormandCardManager;
import com.buaa.divinationmaster.model.DivinationRecord;
import com.buaa.divinationmaster.model.LenormandCard;
import com.buaa.divinationmaster.model.LenormandReading;

import java.util.List;

/**
 * 雷诺曼卡牌页面 - 完整功能实现
 * 36张经典雷诺曼卡牌占卜系统
 */
public class LenormandActivity extends AppCompatActivity {
    
    private EditText etQuestion;
    private CardView cardThreeCard, cardFiveCard, cardNineCard;
    private Button btnStartReading;
    // 移除已删除的 tvSpreadDescription 控件
    
    private LenormandInterpreter.SpreadType selectedSpread = LenormandInterpreter.SpreadType.THREE_CARD;
    private LenormandCardManager cardManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lenormand);
        
        // 应用屏幕适配
        ScreenAdaptationUtil.applyScreenAdaptation(this);
        
        cardManager = LenormandCardManager.getInstance();
        
        setupToolbar();
        initViews();
        setupSpreadSelection();
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("雷诺曼卡牌");
        }
    }
    
    private void initViews() {
        etQuestion = findViewById(R.id.etQuestion);
        cardThreeCard = findViewById(R.id.cardThreeCard);
        cardFiveCard = findViewById(R.id.cardFiveCard);
        cardNineCard = findViewById(R.id.cardNineCard);
        btnStartReading = findViewById(R.id.btnStartReading);
        // tvSpreadDescription 已移除，描述直接显示在卡片内
        
        // 设置开始占卜按钮
        btnStartReading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLenormandReading();
            }
        });
        
        // 默认选中三张牌
        selectSpread(LenormandInterpreter.SpreadType.THREE_CARD);
    }
    
    private void setupSpreadSelection() {
        cardThreeCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectSpread(LenormandInterpreter.SpreadType.THREE_CARD);
            }
        });
        
        cardFiveCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectSpread(LenormandInterpreter.SpreadType.FIVE_CARD);
            }
        });
        
        cardNineCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectSpread(LenormandInterpreter.SpreadType.NINE_CARD);
            }
        });
    }
    
    private void selectSpread(LenormandInterpreter.SpreadType spreadType) {
        selectedSpread = spreadType;
        
        // 重置所有卡片状态
        resetCardSelection();
        
        // 设置选中状态
        CardView selectedCard = null;
        String description = "";
        
        switch (spreadType) {
            case THREE_CARD:
                selectedCard = cardThreeCard;
                description = "过去-现在-未来，简单直接的时间线解读";
                break;
            case FIVE_CARD:
                selectedCard = cardFiveCard;
                description = "问题-障碍-过去-未来-结果，全面分析";
                break;
            case NINE_CARD:
                selectedCard = cardNineCard;
                description = "九宫格牌阵，最详细的生活全景分析";
                break;
        }
        
        if (selectedCard != null) {
            selectedCard.setCardBackgroundColor(getColor(R.color.accent_gold_variant));
            selectedCard.setAlpha(1.0f);
        }
        
        // 描述信息已集成到卡片内，无需单独显示
    }
    
    private void resetCardSelection() {
        cardThreeCard.setCardBackgroundColor(getColor(R.color.surface_dark));
        cardThreeCard.setAlpha(0.8f);
        
        cardFiveCard.setCardBackgroundColor(getColor(R.color.surface_dark));
        cardFiveCard.setAlpha(0.8f);
        
        cardNineCard.setCardBackgroundColor(getColor(R.color.surface_dark));
        cardNineCard.setAlpha(0.8f);
    }
    
    private void startLenormandReading() {
        String question = etQuestion.getText().toString().trim();
        if (question.isEmpty()) {
            etQuestion.setError("请输入占卜问题");
            etQuestion.requestFocus();
            return;
        }
        
        try {
            // 根据牌阵类型抽取对应数量的卡牌
            int cardCount = getCardCount(selectedSpread);
            List<LenormandCard> drawnCards = cardManager.drawCards(cardCount);
            
            // 生成解读
            LenormandReading reading = LenormandInterpreter.performReading(question, selectedSpread, drawnCards);
            
            // 显示结果
            showReadingResult(reading);
            
        } catch (Exception e) {
            Toast.makeText(this, "占卜失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private int getCardCount(LenormandInterpreter.SpreadType spreadType) {
        switch (spreadType) {
            case THREE_CARD: return 3;
            case FIVE_CARD: return 5;
            case NINE_CARD: return 9;
            default: return 3;
        }
    }
    
    private void showReadingResult(final LenormandReading reading) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("🔮 雷诺曼卡牌解读");
        builder.setMessage(reading.generateFullInterpretation());
        builder.setPositiveButton("确定", null);
        builder.setNegativeButton("保存结果", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                saveReadingToDatabase(reading);
            }
        });
        builder.setNeutralButton("查看详情", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showDetailedReading(reading);
            }
        });
        builder.show();
    }
    
    private void showDetailedReading(final LenormandReading reading) {
        StringBuilder detail = new StringBuilder();
        detail.append("【详细卡牌信息】\n\n");
        
        List<LenormandCard> cards = reading.getDrawnCards();
        for (int i = 0; i < cards.size(); i++) {
            LenormandCard card = cards.get(i);
            detail.append("📍 第").append(i + 1).append("张：").append(card.getName())
                  .append(" ").append(card.getSymbol()).append("\n");
            detail.append("关键词：").append(card.getKeywords()).append("\n");
            detail.append("含义：").append(card.getMeaning()).append("\n");
            detail.append("爱情：").append(card.getLove()).append("\n");
            detail.append("事业：").append(card.getCareer()).append("\n");
            detail.append("健康：").append(card.getHealth()).append("\n");
            detail.append("时机：").append(card.getTiming()).append("\n\n");
        }
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("详细卡牌信息");
        builder.setMessage(detail.toString());
        builder.setPositiveButton("确定", null);
        builder.setNegativeButton("分享详情", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                shareReading(reading);
            }
        });
        builder.show();
    }
    
    private void saveReadingToDatabase(LenormandReading reading) {
        DivinationRecord record = new DivinationRecord(
            "lenormand",
            reading.getQuestion(),
            reading.generateCardDataString(),
            reading.generateFullInterpretation(),
            reading.getTimestamp()
        );
        
        DatabaseManager.getInstance(this).saveRecord(record, new DatabaseManager.OnDataCallback<Long>() {
            @Override
            public void onSuccess(Long id) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LenormandActivity.this, "雷诺曼占卜结果已保存", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            
            @Override
            public void onError(Exception error) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LenormandActivity.this, "保存失败：" + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
    
    private void shareReading(LenormandReading reading) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, 
            reading.generateFullInterpretation() + "\n—— 来自占卜大师APP");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "我的雷诺曼卡牌占卜结果");
        
        startActivity(Intent.createChooser(shareIntent, "分享雷诺曼占卜结果"));
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
